package edu.ynu.se.xiecheng.achitectureclass.common.utils.test;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class DeviceDataFetcher {

    // 获取设备采集的数据
    public static List<Map<String, Object>> fetchDeviceData(String token, String boxNo, List<String> ids) {
        // API URL
        String url = "https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo;

        // 请求头配置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token); // 设置 Bearer Token

        // 请求体配置
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("ids", ids);

        try {
            // 将请求体转换为 JSON 格式
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBodyJson = objectMapper.writeValueAsString(requestBody);
            System.out.println("Request Body: " + requestBodyJson);

            // 创建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBodyJson, headers);

            // 发送 POST 请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<List> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, List.class);

            // 判断响应状态
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return response.getBody(); // 返回数据
            } else {
                throw new RuntimeException("Failed to fetch device data. Status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            System.out.println("Error occurred: " + e.getMessage());
            throw new RuntimeException("Failed to fetch device data.", e);
        }
    }


    public static void main(String[] args) {
        // 获取的 Token
        String token = FBoxTokenFetcher.fetchToken(); // 调用之前获取 Token 的方法

        // BoxNo
        String boxNo = "300023040071";

        // 传感器 IDs
        List<String> ids = Arrays.asList(
                "327061330933584660", // 土壤含水率
                "327061330933584661", // 土壤温度
                "327061330932536075", // 土壤电导率
                "327061330932536076", // 土壤 PH 值
                "327061330932536077"  // 土壤氮含量
        );

        // 获取设备数据
        List<Map<String, Object>> deviceData = fetchDeviceData(token, boxNo, ids);

        // 打印获取到的数据
        for (Map<String, Object> data : deviceData) {
            System.out.println(data);
        }
    }
}
